package Service.Impl;

import Dao.RoleMapper;
import Service.RoleService;
import domain.Role;
import domain.RoleMenuVO;
import domain.Role_menu_relation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.instrument.classloading.ResourceOverridingShadowingClassLoader;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    /*
        查询所有角色 +  多条件查询
     */
    @Override
    public List<Role> findAllRole(Role role) {
        List<Role> list = roleMapper.findAllRole(role);
        return list;
    }

    /*
       根据角色id 查询该角色关联的菜单信息 ---> ID[1,2,3..]
     */
    @Override
    public List<Integer> findMenuByRoleId(int roleId) {
        List<Integer> menuByRoleId = roleMapper.findMenuByRoleId(roleId);
        return menuByRoleId;
    }


    /*
          为角色分配菜单
     */
    @Override
    public void saveRoleContextMenu(RoleMenuVO roleMenuVO) {

        //1. 清空中间表的关联关系

        roleMapper.deleteRoleContextMenu(roleMenuVO.getRoleId());

        //2. 为角色分配菜单
        for (Integer mid : roleMenuVO.getMenuIdList()) {

            // 补全参数
            Role_menu_relation relation = new Role_menu_relation();

            relation.setMenuId(mid);
            relation.setRoleId(roleMenuVO.getRoleId());

            //3. 封装数据
            Date date = new Date();
            relation.setCreatedTime(date);
            relation.setUpdatedTime(date);
            relation.setCreatedBy("admin");
            relation.setUpdatedby("admin");


            roleMapper.saveRoleContextMenu(relation);
        }

    }

    /*
        删除角色 (要有清空中间表关联关系方法）
    */
    @Override
    public void deleteRole(int roleid) {

        roleMapper.deleteRoleContextMenu(roleid);
        roleMapper.deleteRole(roleid);

    }
}
